'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '../contexts/AuthContext';
import Layout from '../components/Layout';
import { IconLoader2, IconPlus, IconPencil, IconTrash } from '@tabler/icons-react';

interface DietRecommendation {
  id: string;
  createdAt: string;
  dailyCalories: number;
  macronutrients: {
    protein: number;
    carbs: number;
    fat: number;
  };
  mealPlan: {
    breakfast: string[];
    lunch: string[];
    dinner: string[];
    snacks: string[];
  };
  advice: string;
  tips: string[];
}

interface DietRecord {
  id: string;
  date: Date;
  mealType: string;
  foods: {
    name: string;
    amount: string;
    calories: number;
    protein: number;
    carbs: number;
    fat: number;
  }[];
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
}

export default function DietRecordPage() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const [recommendations, setRecommendations] = useState<DietRecommendation[]>([]);
  const [records, setRecords] = useState<DietRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/login?redirect=/diet-record');
      return;
    }

    if (user) {
      // 获取饮食推荐历史
      fetch('/api/diet/recommendations', { credentials: 'include' })
        .then(res => res.json())
        .then(data => {
          setRecommendations(data.recommendations);
        });

      // 获取饮食记录
      fetchRecords();
    }
  }, [user, authLoading, router]);

  // 获取最近的饮食记录
  const fetchRecords = async () => {
    try {
      const res = await fetch('/api/diet/records', {
        credentials: 'include',
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message);
      setRecords(data.records);
    } catch (error) {
      console.error('获取饮食记录失败:', error);
      setError('获取饮食记录失败');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Layout>
        <div className="flex justify-center items-center min-h-[60vh]">
          <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="max-w-6xl mx-auto px-4 py-8">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-2xl font-bold">饮食记录</h1>
          <button
            onClick={() => router.push('/diet-record/add')}
            className="btn-primary flex items-center gap-2"
          >
            <IconPlus className="w-5 h-5" />
            添加记录
          </button>
        </div>

        {/* 最近的饮食推荐 */}
        {recommendations.length > 0 && (
          <div className="mb-8">
            <h2 className="text-xl font-bold mb-4">最近的饮食推荐</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="bg-blue-50 p-4 rounded-lg">
                <div className="text-sm text-gray-600">推荐热量</div>
                <div className="text-xl font-bold text-blue-600">
                  {recommendations[0].dailyCalories} 千卡
                </div>
              </div>
              <div className="bg-green-50 p-4 rounded-lg">
                <div className="text-sm text-gray-600">蛋白质</div>
                <div className="text-xl font-bold text-green-600">
                  {recommendations[0].macronutrients.protein}g
                </div>
              </div>
              <div className="bg-yellow-50 p-4 rounded-lg">
                <div className="text-sm text-gray-600">碳水化合物</div>
                <div className="text-xl font-bold text-yellow-600">
                  {recommendations[0].macronutrients.carbs}g
                </div>
              </div>
              <div className="bg-red-50 p-4 rounded-lg">
                <div className="text-sm text-gray-600">脂肪</div>
                <div className="text-xl font-bold text-red-600">
                  {recommendations[0].macronutrients.fat}g
                </div>
              </div>
            </div>

            {/* 膳食计划显示 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h3 className="font-medium mb-3">早餐建议</h3>
                <ul className="list-disc list-inside text-gray-600 space-y-1">
                  {recommendations[0].mealPlan.breakfast.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h3 className="font-medium mb-3">午餐建议</h3>
                <ul className="list-disc list-inside text-gray-600 space-y-1">
                  {recommendations[0].mealPlan.lunch.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h3 className="font-medium mb-3">晚餐建议</h3>
                <ul className="list-disc list-inside text-gray-600 space-y-1">
                  {recommendations[0].mealPlan.dinner.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h3 className="font-medium mb-3">零食建议</h3>
                <ul className="list-disc list-inside text-gray-600 space-y-1">
                  {recommendations[0].mealPlan.snacks.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        )}

        {/* 饮食记录部分 */}
        <div>
          <h2 className="text-xl font-bold mb-4">我的饮食记录</h2>
          
          {error && (
            <div className="bg-red-50 text-red-600 p-4 rounded-lg mb-6">
              {error}
            </div>
          )}

          {records.length > 0 ? (
            <div className="space-y-4">
              {records.map(record => (
                <div
                  key={record.id}
                  className="bg-white rounded-lg shadow-sm p-4 hover:shadow-md transition-shadow"
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center gap-4 mb-2">
                        <div className="font-medium text-lg">
                          {new Date(record.date).toLocaleDateString()} - {
                            {
                              'breakfast': '早餐',
                              'lunch': '午餐',
                              'dinner': '晚餐',
                              'snack': '零食'
                            }[record.mealType] || record.mealType
                          }
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => router.push(`/diet-record/edit/${record.id}`)}
                            className="text-gray-500 hover:text-blue-600 p-1 rounded-full hover:bg-blue-50 transition-colors"
                            title="编辑"
                          >
                            <IconPencil className="w-4 h-4" />
                          </button>
                          <button
                            onClick={async () => {
                              if (confirm('确定要删除这条记录吗？')) {
                                try {
                                  const res = await fetch(`/api/diet/record/${record.id}`, {
                                    method: 'DELETE',
                                    credentials: 'include',
                                  });
                                  if (!res.ok) throw new Error('删除失败');
                                  fetchRecords(); // 重新获取记录列表
                                } catch (error) {
                                  console.error('删除记录失败:', error);
                                  setError('删除记录失败');
                                }
                              }
                            }}
                            className="text-gray-500 hover:text-red-600 p-1 rounded-full hover:bg-red-50 transition-colors"
                            title="删除"
                          >
                            <IconTrash className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                      <div className="text-gray-600">
                        {record.foods.map(food => `${food.name} (${food.amount})`).join('、')}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-sm text-gray-600 mb-1">
                        热量: {record.calories} 千卡
                      </div>
                      <div className="text-sm text-gray-600">
                        蛋白质: {record.protein}g | 碳水: {record.carbs}g | 脂肪: {record.fat}g
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="bg-white rounded-lg shadow-sm p-4 text-gray-500">
              还没有饮食记录，开始添加吧！
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
} 